package com.xdxc.component.validation;

import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
import com.xdxc.model.dto.UserAnswerDto;
import org.springframework.stereotype.Component;


@Component
public class AnswerSanitizer {
    // 安全限制配置
    private static final int MAX_ANSWER_LENGTH = 500;
    private static final Pattern DANGEROUS_PATTERN = Pattern.compile(
            "[<>\"'`\\\\]|(script|http:|https:)",
            Pattern.CASE_INSENSITIVE
    );

    public   UserAnswerDto sanitize(UserAnswerDto dto) {
        if (dto == null) {
            return new UserAnswerDto(); // 或返回一个空的 DTO，根据业务需求
        }
        // 1. 深拷贝原始对象（避免污染输入）
        UserAnswerDto sanitizedDto = new UserAnswerDto();
        sanitizedDto.setCheckId(dto.getCheckId()); // 假设ID是安全的
        sanitizedDto.setQuId(dto.getQuId());
        sanitizedDto.setUuId(dto.getUuId());
        sanitizedDto.setAnswerIds(dto.getAnswerIds());
        sanitizedDto.setCheckId(dto.getCheckId());
        sanitizedDto.setPaperId(dto.getPaperId());
        sanitizedDto.setAnswerType(dto.getAnswerType());
        // 2. 清洗 answerText
        String rawAnswer = dto.getAnswerText();
        String cleanAnswer = sanitizeText(rawAnswer);
        sanitizedDto.setAnswerText(cleanAnswer);
        return sanitizedDto;
    }

    private String sanitizeText(String input) {
        if (StringUtils.isBlank(input)) {
            return ""; // 统一处理为空字符串
        }
        // 1. 去除首尾空白
        String trimmed = input.trim();
        // 2. 截断超长内容
        if (trimmed.length() > MAX_ANSWER_LENGTH) {
            trimmed = trimmed.substring(0, MAX_ANSWER_LENGTH);
        }
        // 3. 移除危险字符（如XSS风险）
        return DANGEROUS_PATTERN.matcher(trimmed)
                .replaceAll("");
    }
}